package com.example.locationtest

import android.content.Context
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import com.example.locationtest.databinding.ActivityMainBinding
import com.sscl.baselibrary.activity.BaseViewBindingAppCompatActivity
import android.location.GnssStatus
import android.os.Build
import androidx.annotation.RequiresApi
import com.sscl.baselibrary.utils.BaseManager
import com.sscl.baselibrary.utils.ToastUtil

class MainActivity : BaseViewBindingAppCompatActivity<ActivityMainBinding>() {

    private val gnssStatusCallback = @RequiresApi(Build.VERSION_CODES.N)
    object : GnssStatus.Callback() {
        override fun onSatelliteStatusChanged(status: GnssStatus) {
            val satelliteCount = status.satelliteCount
            var usedSatelliteCount = 0 // 新增：用于统计正在参与定位的卫星数量
            binding.satelliteCountTv.text = satelliteCount.toString()
            val satelliteInfo = mutableMapOf<String, Int>()
            val usedSatelliteInfo = mutableMapOf<String, Int>() // 新增：用于统计正在参与定位的卫星
            for (i in 0 until satelliteCount) {
                val type = status.getConstellationType(i)
                val constellationType = when (type) {
                    GnssStatus.CONSTELLATION_GPS -> "GPS"
                    GnssStatus.CONSTELLATION_GLONASS -> "GLONASS"
                    GnssStatus.CONSTELLATION_BEIDOU -> "BeiDou"
                    GnssStatus.CONSTELLATION_GALILEO -> "Galileo"
                    // 可以根据需要添加更多的卫星系统
                    else -> "Unknown"
                }
                satelliteInfo[constellationType] =
                    satelliteInfo.getOrDefault(constellationType, 0) + 1
                // 检查卫星是否正在用于定位
                if (status.usedInFix(i)) {
                    usedSatelliteInfo[constellationType] =
                        usedSatelliteInfo.getOrDefault(constellationType, 0) + 1
                    usedSatelliteCount++
                }
            }
            println("Total Satellite Count: $satelliteCount, Satellite Info: $satelliteInfo")
            println("Used Satellite Info: $usedSatelliteInfo") // 新增：输出正在参与定位的卫星信息
            //将数据显示在界面上
            BaseManager.handler.post {
                binding.beidouSatelliteCountTv.text = satelliteInfo["BeiDou"]?.toString() ?: "0"
                binding.gpsSatelliteCountTv.text = satelliteInfo["GPS"]?.toString() ?: "0"
                binding.glonassSatelliteCountTv.text = satelliteInfo["GLONASS"]?.toString() ?: "0"
                binding.galileoSatelliteCountTv.text = satelliteInfo["Galileo"]?.toString() ?: "0"
                binding.otherSatelliteCountTv.text = satelliteInfo["Unknown"]?.toString() ?: "0"

                binding.usedSatelliteCountTv.text = usedSatelliteCount.toString()
                binding.beidouUsedSatelliteCountTv.text =
                    usedSatelliteInfo["BeiDou"]?.toString() ?: "0"
                binding.gpsUsedSatelliteCountTv.text = usedSatelliteInfo["GPS"]?.toString() ?: "0"
                binding.glonassUsedSatelliteCountTv.text =
                    usedSatelliteInfo["GLONASS"]?.toString() ?: "0"
                binding.galileoUsedSatelliteCountTv.text =
                    usedSatelliteInfo["Galileo"]?.toString() ?: "0"
                binding.otherUsedSatelliteCountTv.text =
                    usedSatelliteInfo["Unknown"]?.toString() ?: "0"

            }
        }
    }

    private var locationManager: LocationManager? = null

    private val locationListener: LocationListener = object : LocationListener {
        override fun onLocationChanged(location: Location) {
            val latitude = location.latitude
            val longitude = location.longitude
            // 处理获取到的经纬度
            binding.latitudeTv.text = latitude.toString()
            binding.longitudeTv.text = longitude.toString()
        }

        @Deprecated("Deprecated in Java")
        override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {
        }

        override fun onProviderEnabled(provider: String) {}

        override fun onProviderDisabled(provider: String) {}
    }

    /**
     * 在设置布局之前需要进行的操作
     */
    override fun doBeforeSetLayout() {
        locationManager = getSystemService(LOCATION_SERVICE) as LocationManager
    }

    /**
     * 在设置布局之后，进行其他操作之前，所需要初始化的数据
     */
    override fun doBeforeInitOthers() {
        hideTitleBackButton()
    }

    /**
     * 初始化事件
     */
    override fun initEvents() {
    }

    /**
     * 初始化其他数据
     */
    override fun initOtherData() {
    }

    /**
     * 初始化控件数据
     */
    override fun initViewData(savedInstanceState: Bundle?) {
    }

    /**
     * 设置DataBinding
     * 可在此处设置binding的viewModel或观察者等操作
     */
    override fun setBinding() {
    }

    /**
     * 在最后进行的操作
     */
    override fun doAfterAll() {
        try {
            // 请求位置更新
            locationManager?.requestLocationUpdates(
                LocationManager.GPS_PROVIDER,
                0,
                0f,
                locationListener
            )
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                locationManager?.registerGnssStatusCallback(gnssStatusCallback, BaseManager.handler)
            }
        } catch (e: SecurityException) {
            e.printStackTrace()
            ToastUtil.toastLong(this, "系统没有定位能力或者没有开启定位权限")
        }
    }

    /**
     * 标题栏的返回按钮被按下的时候回调此方法
     */
    override fun titleBackClicked(): Boolean {
        return false
    }

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     *
     * 重写方法
     *
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

    override fun onDestroy() {
        super.onDestroy()
        // 移除位置更新监听器，避免资源泄漏
        locationManager?.removeUpdates(locationListener)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            locationManager?.unregisterGnssStatusCallback(gnssStatusCallback)
        }
    }
}